package com.jinlejia.erp.ui.house.prospect;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ViewPagerAdapter;
import com.jinlejia.erp.databinding.ActivityProspectUploadImageBinding;
import com.jinlejia.erp.ui.common.CommonDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.house.prospect.bean.SurveyPictureBean;
import com.weight.CustomToast;

import java.util.ArrayList;

/**
 * 上传或修改房屋照片，户型图
 */
public class ProspectUploadImageActivity extends AppCompatActivity {

    private Helper helper;
    private HousePictureListener housePictureListener;
    private HouseTypePictureListener houseTypePictureListener;

    private String houseSourceCode;
    private String houseSourceType;
    private String houseTypeStr; //0-0-0-0 室-厅-卫-厨
    private String applyCode; //实勘编码
    private int mUsage;
    private String reason; //顶替理由

    private ActivityProspectUploadImageBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_prospect_upload_image);
        binding.rightButton.setOnClickListener(v->save());
        binding.leftButton.setOnClickListener(v->goBack());
        binding.toolbarBackImageView.setOnClickListener(v->goBack());
        helper = Helper.init(this);
        binding.toolbarTitleTextView.setText("实勘图片上传");
        Intent intent = getIntent();
        final int index = intent.getIntExtra(Type.PARAM.IMAGE_SHOW_INDEX, -1);
        //格式:室-厅-卫-厨
        this.houseTypeStr = intent.getStringExtra(Type.PARAM.HOUSE_TYPE);
        mUsage = intent.getIntExtra(Type.PARAM.HOUSE_USAGE_TYPE,-1);
        int showType = intent.getIntExtra(Type.PARAM.IMAGE_SHOW_TYPE,0);
        this.houseSourceCode = intent.getStringExtra(Type.PARAM.HOUSE_SOURCE_CODE);
        this.houseSourceType = intent.getStringExtra(Type.PARAM.HOUSE_SOURCE_TYPE);
        this.applyCode = intent.getStringExtra(Type.PARAM.HOUSE_APPLY_CODE); //实勘编码，只有在更新时才会有
        this.reason = intent.getStringExtra(Type.PARAM.HOUSE_REASON); //顶替理由
        SurveyPictureBean mBean = intent.getParcelableExtra(Type.PARAM.HOUSE_SOURCE_INFO);
        int pageType = intent.getIntExtra(Type.PARAM.PAGE_TYPE,0);
        helper = Helper.init(this);
        helper.message().closeMessage();
        final ArrayList<Fragment> mFragments = new ArrayList<>();
        ArrayList<String> titles = new ArrayList<>();
        if (showType==1 || showType==0){
            this.housePictureListener = loadHousePictureListener(pageType,mUsage, houseTypeStr,this.houseSourceCode,this.houseSourceType, mBean);
            titles.add("房屋照片");
            mFragments.add(0, (Fragment) housePictureListener);       //房屋照片
        }else if (showType==2){ //仅仅上传户型图
            titles.add("户型图照片");
            this.houseTypePictureListener = ProspectUploadHouseTypeFragment.newInstance(pageType, houseTypeStr,this.houseSourceCode,this.houseSourceType,mBean);
            mFragments.add(0, (Fragment) houseTypePictureListener);   //户型图照片
            this.binding.houseTypeTextView.setVisibility(View.VISIBLE);
            this.binding.houseTypeTextView.setOnClickListener(v -> toChooseListApartment());
        }
        if (showType==0){
            titles.add("户型图照片");
            this.binding.houseTypeTextView.setVisibility(View.VISIBLE);
            this.binding.houseTypeTextView.setOnClickListener(v -> toChooseListApartment());
            this.houseTypePictureListener = ProspectUploadHouseTypeFragment.newInstance(pageType, houseTypeStr,this.houseSourceCode,this.houseSourceType,mBean);
            mFragments.add(1, (Fragment) houseTypePictureListener);    //户型图照片
        }else if (showType==1){
            this.binding.houseTypeTextView.setVisibility(View.GONE);
            this.binding.houseTypeTextView.setOnClickListener(null);
        }
        String[]titleStr = titles.toArray(new String[titles.size()]);
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this.getSupportFragmentManager(), titleStr, mFragments);
        binding.viewPager.setAdapter(viewPagerAdapter);
        binding.viewPager.setOffscreenPageLimit(mFragments.size());

        //noinspection deprecation
        binding.tabLayout.setTabsFromPagerAdapter(viewPagerAdapter);
        binding.tabLayout.post(() -> {
            // 将TabLayout和ViewPager进行关联，让两者联动起来
            binding.tabLayout.setupWithViewPager(binding.viewPager);
            if (index != -1 && mFragments.size()<index){
                binding.viewPager.setCurrentItem(index);
            }
        });

        if (!TextUtils.isEmpty(houseTypeStr) && !"null".equalsIgnoreCase(houseTypeStr)) {
            Helper.Util.HouseInfo info = helper.util().formatHouseInfo(houseTypeStr);
            helper.message().showHouseInfo(mUsage, info);
        }else {
            helper.message().showHouseInfo(mUsage);
        }
        String rejectReason = intent.getStringExtra(Type.PARAM.REJECT_REASON);
        if (!TextUtils.isEmpty(rejectReason)){
            helper.message().showErrorMessage(rejectReason);
        }
    }

    private HousePictureListener loadHousePictureListener(int pageType, int usage, String houseType, String houseSourceCode, String houseSourceType, SurveyPictureBean bean) {
        return FragmentHelper.newInstance(pageType,usage,houseType,houseSourceCode,houseSourceType,bean);
    }

    //选择户型图
    private void toChooseListApartment(){
        Intent intent = new Intent();
        intent.setClass(this,ProspectChooseHouseTypeActivity.class);
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_CODE,houseSourceCode);  //房源编码
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_TYPE,houseSourceType);  //房源类型
        intent.putExtra(Type.PARAM.HOUSE_TYPE,houseTypeStr);          //房屋户型
        intent.putExtra(Type.PARAM.HOUSE_USAGE_TYPE,this.mUsage);       //房屋用途类型
        Fragment fragment = (Fragment) this.houseTypePictureListener;
        if (housePictureListener!=null && houseTypePictureListener!=null){ //在选择户型图库时，先跳转到户型图照片标签页
            binding.viewPager.setCurrentItem(1);
        }else if (houseTypePictureListener!=null){
            binding.viewPager.setCurrentItem(0);
        }
        fragment.startActivityForResult(intent,10);
    }

    private final int MIN_DELAY_TIME = 1000;  // 两次点击间隔不能少于1000ms
    private long lastClickTime;
    private boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }
    private CommonDialog dialog;
    public void save() {
        if (isFastClick())return;
        SurveyPictureBean bean = null;
        if (housePictureListener != null) { //检查房屋图片上传
            String result = housePictureListener.checkPicturesResult();
            if (!TextUtils.isEmpty(result)){
                CustomToast.showToast(this,result,2000);
                return;
            }
            bean = housePictureListener.getPicturesResult();
            String usageType = helper.message().getUsageNameByUsageType(mUsage);
            bean.setPurpose(usageType); //房屋用途
            if (houseTypePictureListener==null){ //仅仅更新房屋图片
                uploadInfoToServer(bean);
                return;
            }
        }

        //当用户没有上传户型信息时，提示用户去上传，当用户选择不上传时，或者上传完户型图时，
        //调用uploadInfoToServer()执行上传操作
        if (houseTypePictureListener != null) {
            String message = houseTypePictureListener.hahHouseTypePicture();
            if (!TextUtils.isEmpty(message)){ //如果没有上传户型图
                if (housePictureListener==null){ //如果仅仅上传户型图时
                    CustomToast.showToast(this,message,1500);
                    return;
                }
                final SurveyPictureBean fBean = bean;
                if (dialog!=null){
                    dialog.dismiss();
                    dialog = null;
                }
                //如果既上传，房屋图，又上传户型图时，对话框提示用户进行上传户型图
                dialog = new CommonDialog(this,"提示","还没上传户型图，请上传户型图!","上传","取消");
                dialog.setConfirmListener(() -> { //跳转至上传户型标签页
                    TabLayout.Tab tab = binding.tabLayout.getTabAt(1);
                    if (tab != null) {
                        tab.select();
                    }
                });
                dialog.setCancelable(true);
                dialog.show();

            }else { //当用户上传了户型图时
                if (housePictureListener==null){ //如果仅仅上传户型图
                    SurveyPictureBean temp = houseTypePictureListener.getHouseTypeResult();
                    uploadInfoToServer(temp);
                }else {
                    SurveyPictureBean temp = houseTypePictureListener.getHouseTypeResult();
                    if (bean==null)throw new NullPointerException("未知错误"); //理论不会抛出这个异常
                    bean.setApartment(temp.getApartment());
                    uploadInfoToServer(bean);
                }
            }
        }
    }

    private ProgressDialog progressDialog;
    private void uploadInfoToServer(SurveyPictureBean bean){
        if (!TextUtils.isEmpty(this.reason)){
            bean.setReason(this.reason);
        }
        bean.setRscode(houseSourceCode);
        if (progressDialog==null){
            progressDialog = new ProgressDialog(this,"上传中...",false);
        }
        if (houseTypePictureListener != null){ //1. 如果可以上传或者更新户型图
            if (housePictureListener != null){ //2. 并且可以上传或者更新房屋信息，则进行上传or更新实勘信息请求
                progressDialog.show();
                helper.http().saveSurveyPicture(houseSourceType, applyCode,bean, result -> {
                    progressDialog.dismiss();
                    if (result){
                        setResult(Activity.RESULT_OK);
                        finish();
                    }
                });
            }else { //2. 如果不可以上传或更新房屋信息，则进行补充户型图请求
                progressDialog.show();
                helper.http().saveApartmentPicture(houseSourceType, bean.getApartment(), bean.getRscode(), new Helper.Http.SaveApartmentPictureCallBack() {
                    @Override
                    public void onSuccess() {
                        progressDialog.dismiss();
                        setResult(Activity.RESULT_OK);
                        finish();
                    }

                    @Override
                    public void onFailed() {
                        progressDialog.dismiss();
                    }
                });
            }
        }else { //1.如果不可以上传户型图，则进行上传or更新实勘房屋信息
            progressDialog.show();
            helper.http().saveSurveyPicture(houseSourceType, applyCode,bean, result -> {
                progressDialog.dismiss();
                if (result){
                    setResult(Activity.RESULT_OK);
                    finish();
                }
            });
        }
    }

    public void goBack() {
        this.finish();
    }

    @Override
    protected void onDestroy() {
        if (dialog!=null){
            dialog.dismiss();
        }
        dialog = null;

        if (progressDialog!=null){
            progressDialog.dismiss();
        }
        progressDialog = null;
        helper.release();
        super.onDestroy();
    }

    interface HousePictureListener {
        String checkPicturesResult();
        SurveyPictureBean getPicturesResult();
    }

    interface HouseTypePictureListener {
        String hahHouseTypePicture();
        SurveyPictureBean getHouseTypeResult();
    }
}
